<template>
  <div class="detail">
    <el-dialog v-if="detail" v-model="detailVisible" :title="detail.title" width="900" draggable style="height: 500px"
      :before-close="cancel">
      <div class="main" style="height: 430px">
        <div class="detail-image">
          <v-carousel hide-delimiters progress="primary" class="images-container" v-if="detail.images">
            <template v-slot:prev="{ props }">
              <el-icon :size="20" class="hover-scale">
                <ArrowLeft variant="elevated" @click="handleClick(props, 0)" />
              </el-icon>
            </template>
            <template v-slot:next="{ props }">
              <el-icon :size="20" class="hover-scale">
                <ArrowRight variant="elevated" @click="handleClick(props, 1)" />
              </el-icon>
            </template>

            <!-- bug，轮播图第一张图不能v-for -->
            <v-carousel-item cover>
              <img class="image" @click="onBig(detail.images[0])" :src="detail.images[0]"></img>
            </v-carousel-item>
            <v-carousel-item v-for="(item, index) in detail.images.slice(1)" :key="index" cover>
              <img class="image" @click="onBig(item)" :src="item"></img>
            </v-carousel-item>
          </v-carousel>
          <span v-if="detail.images" class="current-image">
            {{ currentImageNum + 1 }}/{{ detail.images.length }}
          </span>
        </div>
        <div class="detail-content">
          <el-scrollbar height="390px" style="padding-right: 10px">
            <div class="header">
              <div class="avatar-username">
                <el-avatar :size="30" :src="detail.avatar" />
                <span class="name">{{ detail.username }}</span>
              </div>
              <el-button>关注</el-button>
            </div>
            <el-divider style="margin: 0; margin-top: 5px" />
            <div class="body">
              <h4>{{ detail.title }}</h4>
              <div class="body-content">
                <p>{{ detail.content }}</p>
              </div>
              <Tag v-for="(item, index) in detail.tags" :key="index">{{ item }}</Tag>
              <div>{{ dateFormat(detail.lastTime) }}</div>
              <el-divider style="margin: 0; margin: 5px 0 10px 0" />
            </div>
            <div class="common-list" v-if="detail.comments">
              <Comment v-if="comments.length > 0" v-for="comment in comments" :obj="comment"
                @deleteComment="initComments" @updateCommentCount="initComments"></Comment>
              <el-empty v-else description="暂无评论" />
            </div>
          </el-scrollbar>
        </div>
        <div class="footer">
          <el-input v-model="newComment" style="width: 240px" placeholder="期待你的精彩评论..." maxlength="100" show-word-limit
            clearable @keyup.enter="PostNewComment" />
          <el-button type="primary" style="margin-right: 10px" :disabled="newComment.length === 0"
            @click="PostNewComment">
            发布
          </el-button>
          <div class="action">
            <div class="post-likes">
              <button class="like-button" :class="{ liked: likeState }" @click="toggleLike">
                <font-awesome-icon :icon="['far', 'heart']" v-if="!likeState" />
                <font-awesome-icon :icon="['fas', 'heart']" v-else />
              </button>
              <span class="count">{{ likeCount }}</span>
            </div>
            <div class="post-favorites">
              <button class="favorite-button" :class="{ favorite: isFavorite }" @click="toggleFavorite">
                <font-awesome-icon :icon="['far', 'star']" v-if="!isFavorite" />
                <font-awesome-icon v-else :icon="['fas', 'star']" />
              </button>
              <span class="count">{{ favoriteCount }}</span>
            </div>
            <div class="post-comments">
              <el-icon size="19" style="color: #000; margin: 1px 6px 0 6px; cursor: pointer">
                <ChatLineRound />
              </el-icon>
              <span class="count">{{ commentsCount }}</span>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { favoritePost, getComments, getDetailPost, isFavoritePost, PostComment, thumbsUp } from '@/api/forum'
import { dateFormat } from '@/utils/strutils'
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome'
import { nextTick, ref } from 'vue'
import Tag from './Tag.vue'
import Comment from '../../../components/Comment.vue'
import { startLoading, stopLoading } from '@/utils/loading'
import { ElNotification } from 'element-plus'
import { getFile } from '@/utils/fileutils'

const props = defineProps({
  id: String
})

const emit = defineEmits(['close'])

// 文章内容显示框
const detailVisible = ref(true)

// 获取文章详情
const detail = ref({})

// 显示图片
const currentImageNum = ref(0)

// 点击轮播
const handleClick = (props, type) => {
  props.onClick()
  if (type === 0) {
    currentImageNum.value =
      currentImageNum.value - 1 < 0 ? detail.value.images.length - 1 : currentImageNum.value - 1
  } else {
    currentImageNum.value =
      currentImageNum.value + 1 >= detail.value.images.length ? 0 : currentImageNum.value + 1
  }
}

// 评论总数
const commentsCount = ref(0)

const initDetails = async () => {
  const id = props.id
  startLoading()
  const { data } = (await getDetailPost(id)).data
  // 将图片转化为blob url 以便于显示图片
  data.images.forEach(async (image, i, images) => {
    images[i] = await getFile(image)
  })
  data.avatar = await getFile(data.avatar)

  stopLoading()
  detail.value = data
  likeState.value = data.favorite
  likeCount.value = data.liked
  favoriteCount.value = data.favoriteNum
  checkFavorite()
}

nextTick(() => {
  initDetails()
})

// 获取评论
const comments = ref([])

const initComments = async () => {
  startLoading()
  const { data } = (await getComments(props.id)).data
  stopLoading()

  comments.value = []
  comments.value = data

  if (comments.value.length === 0) {
    return
  }
  const totalChildNum = comments.value.reduce((sum, comment) => {
    return sum + comment.childNum
  }, 0)
  commentsCount.value = totalChildNum + comments.value.length
}

initComments()

// 新评论
const newComment = ref('')

// 发表评论
const PostNewComment = async () => {
  startLoading()
  const res = (await PostComment({ recordId: props.id, content: newComment.value })).data
  stopLoading()
  if (res.success) {
    newComment.value = ''
    await initComments()
  } else {
    ElNotification({
      title: '错误',
      message: '发布评论失败，请稍后重试',
      type: 'error'
    })
  }
}

// 是否点赞
const likeState = ref()

// 喜爱数量
const likeCount = ref()

// 点赞
const toggleLike = async () => {
  likeState.value = !likeState.value
  const { data } = (await thumbsUp(detail.value.id)).data
  // 获取改记录总体点赞数量
  likeCount.value = data
}

// 是否收藏
const isFavorite = ref(true)

// 收藏数量
const favoriteCount = ref()

const checkFavorite = async () => {
  const { data } = (await isFavoritePost(detail.value.id)).data
  isFavorite.value = data
}

// 收藏
const toggleFavorite = async () => {
  isFavorite.value = !isFavorite.value
  const { data } = (await favoritePost(detail.value.id)).data
  favoriteCount.value = data
}

// 关闭对话框
const cancel = () => {
  emit('close')
}

// 点击图片放大
const onBig = (data) => {
  ElMessageBox.alert(
    `<img src="${data}" style="max-width: 100%; height: auto; display: block; margin: 0 auto;" />`,
    '预览',
    {
      dangerouslyUseHTMLString: true,
      draggable: true,
      confirmButtonText: '关闭'
    }
  )
}
</script>

<style scoped less="scss">
.detail {
  .main {
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 5px;

    position: relative;

    .detail-image {
      width: 38%;
      height: 430px;

      .current-image {
        display: block;
        width: 100%;
        text-align: center;
        font-size: 1.1rem;
      }

      .images-container {
        position: relative;

        height: 410px !important;
        border-radius: 3px;
        overflow: hidden;

        .image {
          width: 100%;
          display: block;
          height: auto;
          cursor: pointer;

          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
          border-radius: 5px;
        }

        .image::before {
          content: '';
          font-family: 'Font Awesome 5 Free';
          font-weight: 900;
          color: transparent;
          position: absolute;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
          display: flex;
          justify-content: center;
          align-items: center;
          background-size: 100% 100%;
          border-radius: 5px;
          transition: background-color 0.3s;
          z-index: 1;
        }

        .image:hover::before {
          position: absolute;
          color: white;
          font-size: 1.5rem;
          background-color: rgba(0, 0, 0, 0.3);
          z-index: 5;
        }

        .hover-scale {
          width: 40px;
          height: 40px;
          cursor: pointer;
          color: transparent;
          border-radius: 40px;
          transition: all 0.5s;
        }

        .hover-scale:hover {
          color: #333;
          background-color: white;
          opacity: 0.5;
          transform: scale(1.1);
        }
      }
    }

    .detail-content {
      width: 58%;
      height: 100%;

      .header {
        display: flex;
        justify-content: space-around;
        align-items: center;

        padding: 0 20px 0 10px;

        .avatar-username {
          display: flex;
          justify-content: start;
          align-items: center;
          gap: 5px;

          width: 100%;
          height: 40px;
        }
      }
    }

    .footer {
      position: absolute;
      right: 0;
      bottom: 0;

      display: flex;
      align-items: center;
      gap: 10px;

      width: 58%;
      height: 35px;

      .action {
        display: flex;
        justify-content: space-between;
        align-items: center;

        width: 30%;

        .post-likes,
        .post-favorites,
        .post-comments {
          display: flex;
          align-items: center;
          justify-content: center;

          .like-button,
          .favorite-button {
            width: 28px;
            height: 22px;
            background: none;
            border: none;
            cursor: pointer;
            font-size: 1.2em;
            color: #333;
            margin-right: 3px;
          }

          .count {
            display: inline-block;

            height: 25px;
            text-align: center;
            line-height: 28px;
          }

          .like-button.liked {
            color: red;
          }

          .favorite-button.favorite {
            color: rgb(235, 180.6, 99);
          }
        }
      }
    }
  }
}
</style>
